<?php

App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 */
class UsersController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator','Session');
        public $helpers = array('Form', 'Html', 'Js', 'Time','Session');

/**
 * index method
 *
 * @return void
 */
         public function beforeFilter() {
      
        $this->Auth->allow('add','resent', 'login','forgotpws','resetemail');
        $this->set('params','');
    }
	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->Paginator->paginate());
	}
        public function login() {
            if ($this->request->is('post')) {
               $user = $this->request->data['User']['username'];
               $role = $this->request->data['User']['role'];
               $check = $this->User->find('first', array(
                    'conditions' => array('User.username' => $user)
                 ));
//               echo $check['User']['status'];
//               die();
               // check user activated
               if($check['User']['status']==1) {
                    if ($this->Auth->login()) { 
                        if ($this->Auth->user('role') && $this->Auth->user('role')=='Admin'){
                            return $this->redirect(array(
                                'controller' => 'products',
                                'action' => 'index'));
                        }else{
                            return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'adsadd'));
                        }
                    }
                    else{
                         $this->Session->setFlash(__('Invalid username or password, try again'));
                         if($role=='admin'){
                             return $this->redirect(array(
                                'controller' => 'users',
                                'action' => 'login'));
                         }else {
                        return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'login'));
                         }
                    }
                    
               } elseif (!empty($check) && $check['User']['status']==0) {
                 $this->Session->setFlash(__('User not yet acivated'));
                 return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'activated'));
               }else{
                    $this->Session->setFlash(__('You do not have account yet'));
                     if($role=='admin'){
                             return $this->redirect(array(
                                'controller' => 'users',
                                'action' => 'login'));
                         }else {
                        return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'login'));
                         }
                   }
            
            }
        }
        public function logout() {
             if($this->Auth->logout()){ 
                 return $this->redirect(array(
                                'controller' => 'users',
                                'action' => 'login'));         
             }
        }
/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */

           
        public function resent(){
            if ($this->request->is('post')) {
                 $email = $this->request->data['User']['email'];
                $check = $this->User->find('first', array(
                    'conditions' => array('User.email' => $email)
                 ));
                 if(empty($check)){
                      $this->Session->setFlash(__('Email account is not exist!'));
                      $this->redirect(array('controller' => 'posts', 'action' => 'resent')); 
                          $this->Session->setFlash(__('Email account is not exist!'));
                 } else {
                      $this->Session->setFlash(__('Activate Code has been sent!'.$check['User']['token']));
                       $user_message = "Thank you for using phsarkhmer services which is the best market ads listing in Cambodia. Activated Code: '".$check['User']['token']."'";                     
                                    $to      =  $email;
                                    $subject = 'Activate Code -Phsarkhmer';
                                    $message = $user_message;
                                    $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                                        'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                                    mail($to, $subject, $message, $headers);
                                    
				//return $this->redirect(array('action' => 'index'));
                                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'activated'));         
                 }
            }
        }
	public function add() {  
		if ($this->request->is('post')) {
                  $id=$this->User->find('first', array('order' => array('User.id' => 'DESC')));
                  $code= rand(100, 999).$id['User']['id'];
                  
                        // $token=$this->request->data['User']['username'];
                  $user_email=$this->request->data['User']['email'];
             
			$this->User->create();
                        $this->User->set('token',$code);
			if ($this->User->save($this->request->data)) {
                                    $this->Session->setFlash(__('The you has been registered. please check your email to get activated code'));
                                
                                    $user_message = "Thank you for your register with phsarkhmer which is the best market ads listing in Cambodia. Activated Code: '".$code."'";                     
                                    $to      =  $user_email;
                                    $subject = 'Activate Account -Phsarkhmer';
                                    $message = $user_message;
                                    $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                                        'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                                    mail($to, $subject, $message, $headers);
                                    
				//return $this->redirect(array('action' => 'index'));
                                return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'activated'));         
             
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$locations = $this->User->Location->find('list');
		$this->set(compact('locations'));
	}
    
                               
/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */ 
public function forgotpws(){
                $encrypt = false;
                $key = 'encrypt';
                // initialization vector 
                $iv = md5(md5($key));
               if ($this->request->is('post')){
                  
		 $email = $this->request->data['User']['email'];
                 $check = $this->User->find('first', array(
                    'conditions' => array('User.email' => $email)
                 ));
                 if(empty($check)){
                      $this->Session->setFlash(__('Email account is not exist!'));
                      $this->redirect(array('controller' => 'posts', 'action' => 'forgotpws')); 
                 }  else {
                     $encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $check['User']['id'], MCRYPT_MODE_CBC, $iv);
                      $encrypt = base64_encode($encrypt);
                     $this->Session->setFlash(__('Email has been sent to your email address. please check it to reset your new password'));
                     $idscript=str_replace(" ", "+", $encrypt);
                    //  echo $idscript;
                       $user_message = "To change your new password please click link below \n http://phsarkhmer.biz/users/resetemail/".$idscript."'";                     
                                    $to      =  $email;
                                    $subject = 'Reset Password -Phsarkhmer';
                                    $message = $user_message;
                                    $headers = 'From: no-reply@phsarkhmer.biz' . "\r\n" .
                                        'Reply-To: no-reply@phsarkhmer.biz' . "\r\n";
                                    mail($to, $subject, $message, $headers);
                       
                    //change it to send an email when it live
                    // $this->redirect(array('controller' => 'Users', 'action' => 'resetemail',$encrypt)); 
                         return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'msregister'));         
             
                 }
                }
}
public function activated(){
      if ($this->request->is('post')){
         $token=$this->request->data['User']['token'];
         $code = $this->User->find('first', array(
                    'conditions' => array('User.token' => $token)
                 ));
         if($code){
            $this->User->updateAll(
                    array( 'User.status' => 1),   //fields to update
                    array( 'User.token' => $token)  //condition  
                );
             $this->Session->setFlash(__('Activated!'));
         } else {
             $this->Session->setFlash(__('Activated Code is incorrect'));
         }
     }
}
public function resetemail($id=null){
   
    $idscript=str_replace(" ", "+", $id);
  //  echo $idscript;
 //   echo '<a href="'.$this->webroot.'Users/resetemail/'.$idscript.'">reset</a>';
        $descrypt = false;
        $key = 'encrypt';
        // initialization vector 
        $iv = md5(md5($key));
        $descrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($idscript), MCRYPT_MODE_CBC, $iv);
        $descrypt = rtrim($descrypt, "");
        $ids=trim($descrypt);
      //  echo $ids;
     if ($this->request->is('post')){
        $pass=$this->request->data['User']['password'];
       
        $password = AuthComponent::password($pass);
        $this->User->updateAll(
                array( 'User.password' => "'".$password."'"),   //fields to update
                array( 'User.id' => $ids)  //condition  
            );
         return $this->redirect(array(
                                'controller' => 'posts',
                                'action' => 'login'));   
     
     }
 
}
public function edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
		$locations = $this->User->Location->find('list');
		$this->set(compact('locations'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}}
